import api from "../api/api";
import tip from "./tip.js";
import sensors from '@/js_sdk/Sensorsdata-UniPlugin-JS/Sensorsdata-UniPlugin-JS/index.js'
import commonSensors from '@/utils/commonSensors.js'
import {
  SYSTEM_INFO,
  MERCHANT_INFO,
  CUSTOMER_INFO,
  USER_INFO,
  USER_SPECICAL_INFO,
  MEMBER_INFO,
} from "./constant.js";

function getCurrentTime() {
  let keep = "";
  let date = new Date();
  let y = date.getFullYear();
  let m = date.getMonth() + 1;
  m = m < 10 ? "0" + m : m;
  let d = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  let h = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
  let f = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
  let s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  keep = y + "" + m + "" + d + "" + h + "" + f + "" + s;
  return keep; // 20160614134947
}

function objLength(input) {
  let type = toString(input);
  let length = 0;
  if (type !== "[object Object]") {
    // throw '输入必须为对象{}！'
  } else {
    for (let key in input) {
      if (key !== "number") {
        length++;
      }
    }
  }
  return length;
}
// 验证是否是手机号码
function vailPhone(number) {
  let flag = true;
  let myreg =
    /^(((13[0-9]{1})|(14[0-9]{1})|(17[0]{1})|(15[0-3]{1})|(15[5-9]{1})|(18[0-9]{1}))+\d{8})$/;
  if (number.length !== 11 || !myreg.test(number)) {
    flag = false;
  }
  return flag;
}
// 验证是否西班牙手机(6开头 9位数)
function ifSpanish(number) {
  let flag = true;
  let myreg = /^([6|7|9]{1}(\d+){8})$/;
  if (number.length !== 9 || !myreg.test(number)) {
    flag = false;
  }
  return flag;
}
// 浮点型除法
function div(a, b) {
  let c, d, e, f;
  try {
    e = a.toString().split(".")[1].length;
  } catch (g) {}
  try {
    f = b.toString().split(".")[1].length;
  } catch (g) {}
  // [eslint] Return statement should not contain assignment. (no-return-assign)
  c = Number(a.toString().replace(".", ""));
  d = Number(b.toString().replace(".", ""));
  return mul(c / d, Math.pow(10, f - e));
}
// 浮点型加法函数
function accAdd(arg1, arg2) {
  let r1, r2, m;
  try {
    r1 = arg1.toString().split(".")[1].length;
  } catch (e) {
    r1 = 0;
  }
  try {
    r2 = arg2.toString().split(".")[1].length;
  } catch (e) {
    r2 = 0;
  }
  m = Math.pow(10, Math.max(r1, r2));
  return ((arg1 * m + arg2 * m) / m).toFixed(2);
}
// 浮点型乘法
function mul(a, b) {
  let c = 0;
  let d = a.toString();
  let e = b.toString();
  try {
    c += a.toString().split(".")[1].length;
  } catch (f) {}
  try {
    c += b.toString().split(".")[1].length;
  } catch (f) {}
  return (
    (Number(d.replace(".", "")) * Number(e.replace(".", ""))) / Math.pow(10, c)
  );
}

//  遍历对象属性和值
function displayProp(obj) {
  let names = "";
  for (let name in obj) {
    names += name + obj[name];
  }
  return names;
}
//  去除字符串所有空格
function sTrim(text) {
  return text.replace(/\s/g, "");
}
// 去除所有:,英文冒号
function replaceColon(txt) {
  return txt.replace(/:/g, "");
}
// 转换星星分数
function convertStarArray(score) {
  // 1 全星,0 空星,2半星
  let arr = [];
  for (let i = 1; i <= 5; i++) {
    if (score >= i) {
      arr.push(1);
    } else if (score > i - 1 && score < i + 1) {
      arr.push(2);
    } else {
      arr.push(0);
    }
  }
  return arr;
}
// UTC转为北京时间
function UTCformat(utc) {
  var date = new Date(utc),
    y = date.getFullYear(),
    month =
      date.getMonth() + 1 > 9
        ? date.getMonth() + 1
        : "0" + parseInt(date.getMonth() + 1),
    day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate(),
    h = date.getHours() > 9 ? date.getHours() : "0" + date.getHours(),
    m = date.getMinutes() > 9 ? date.getMinutes() : "0" + date.getMinutes(),
    s = date.getSeconds() > 9 ? date.getSeconds() : "0" + date.getSeconds();
  var res = y + "-" + month + "-" + day + " " + h + ":" + m;
  return res;
}
// 13位时间戳转日期
function timeFormat(time, flag) {
  var date = new Date(time); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  let Y, M;
  if (flag) {
    Y = date.getFullYear() + "-";
    M =
      (date.getMonth() + 1 < 10
        ? "0" + (date.getMonth() + 1)
        : date.getMonth() + 1) + "-";
  } else {
    Y = date.getFullYear() + "/";
    M =
      (date.getMonth() + 1 < 10
        ? "0" + (date.getMonth() + 1)
        : date.getMonth() + 1) + "/";
  }
  var D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
  var h =
    (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
  var m =
    (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
    ":";
  var s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();

  let strDate = Y + M + D + h + m + s;
  return strDate;
}
// 13位时间戳转日期  不补0
function noZeroFormat(time, flag) {
  var date = new Date(time); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  let Y, M;
  Y = date.getFullYear() + ".";
  M = date.getMonth() + 1 + ".";

  var D = date.getDate();
  let strDate = Y + M + D;
  return strDate;
}
/**
 * [isDuringDate 比较当前时间是否在指定时间段内]
 * @author Tiamo
 * @DateTime 2021-12-20
 * @param    date   [beginDateStr] [开始时间]
 * @param    date   [endDateStr]   [结束时间]
 * @return   Boolean
 */
function isDuringDate(beginDateStr, endDateStr) {
  let curDate = new Date(),
    beginDate = new Date(beginDateStr),
    endDate = new Date(endDateStr);
  if (curDate >= beginDate && curDate <= endDate) {
    return true;
  }
  return false;
}
// 转时间戳
function formatTimeStamp(date) {
  let systemInfo = uni.getStorageSync(SYSTEM_INFO);
  let isIos = systemInfo.system.indexOf("iOS");
  if (isIos == 0) {
    date = date && new Date(date.replace(/-/g, "/")).getTime();
  } else {
    date = date && new Date(date).getTime();
  }
  return date;
}

// 根据id查询活动消息详情
/**
 * @param {Object} activitySubscribeNavigate 判断是否可跳转，默认可跳转
 * @param {Object} activityId 活动id
 * @param {Boolean} type 类型  文章订阅 articleSubscribe
 */
async function getActivitySubscribeDetail(
  activityId,
  activitySubscribeNavigate,
  type
) {
  let that = this;
  if (activityId) {
    const customerInfo = uni.getStorageSync(CUSTOMER_INFO) || {};
    let result = null;
    if (customerInfo.jwt) {
      result = await api.queryActivitySubscribeDetail(
        {
          header: {
            jwt: customerInfo.jwt,
            "content-type": "application/json;charset=UTF-8",
          },
        },
        activityId
      );
    } else {
      const merchantInfo = uni.getStorageSync(MERCHANT_INFO);
      result = await api.queryGuestActivitySubscribeDetail(
        {},
        activityId,
        merchantInfo?.cloudMerchantId
      );
    }
    // console.log("zlk getActivitySubscribeDetail result:", {  activityId,
      // activitySubscribeNavigate,
      // type, result});
    if (type == "articleSubscribe" || type == "targetActivity") {
      return result;
    } else {
      if (result.code === 1000) {
        let data = result.data;
        let state = data.state;
        let pageAfterSubscribe = data.pageAfterSubscribe || "";
        if (state == 1) {
          //启用状态
          let templateId = data.templateId;
          getCustomerSubscribeInfo(
            activityId,
            templateId,
            pageAfterSubscribe,
            activitySubscribeNavigate,
            type
          );
        } else {
          tip.plainText("活动已结束");
        }
      } else {
        tip.plainText("订阅失败");
      }
    }
  }
}

// 查询用户订阅状态
async function getCustomerSubscribeInfo(
  activitySubscribeId,
  templateId,
  pageAfterSubscribe,
  activitySubscribeNavigate,
  type
) {
  const customerInfo = uni.getStorageSync(CUSTOMER_INFO) || {};
  if (activitySubscribeId) {
    const request = customerInfo.jwt
      ? api.getweixinSubscribe
      : api.getGuestWeixinSubscribe;
    const merchantInfo = uni.getStorageSync(MERCHANT_INFO);
    const userSpecialInfo = uni.getStorageSync(USER_SPECICAL_INFO);
    const query = {
      name: "活动模版消息",
      appId: getApp().globalData.app_id,
      openId: customerInfo?.openId || userSpecialInfo?.openid,
      merchantId: merchantInfo?.cloudMerchantId,
      params: {
        activitySubscribeId: activitySubscribeId,
      },
    };
    const result = await request({
      method: "POST",
      header: {
        jwt: customerInfo.jwt || "",
      },
      query: query,
    });
    // console.log("zlk getCustomerSubscribeInfo result:", { result, query });
    if (type == "articleSubscribe" || type == "targetActivity") {
      return result;
    } else {
      if (result.code == 1000) {
        //已订阅
        tip.plainText("已订阅");
        if (!pageAfterSubscribe) {
          return;
        } else {
          if (activitySubscribeNavigate == "false") {
            return;
          }
          uni.navigateTo({
            url: `/${pageAfterSubscribe}`,
          });
        }
        return;
      } else if (result.code == -1010) {
        //未订阅
        requestSubscribe(
          activitySubscribeId,
          templateId,
          pageAfterSubscribe,
          activitySubscribeNavigate,
          type
        );
      } else {
        tip.plainText(result.msg);
      }
    }
    return;
  }
}

function requestSubscribe(
  activitySubscribeId,
  templateId,
  pageAfterSubscribe,
  activitySubscribeNavigate,
  type
) {
  let tmplIds = [];
  tmplIds.push(templateId);
  commonSensors.popupEvent('PopupExposure', {'popup_type' : '订阅消息', 'popup_name': '订阅消息弹窗'})
  commonSensors.modelAuthAsk('活动', tmplIds)
  uni.requestSubscribeMessage({
    tmplIds: tmplIds,
    success(res) {
      if (res[templateId] == "accept") {
        // 用户允许接收订阅消息
        doSubscribe(
          activitySubscribeId,
          pageAfterSubscribe,
          activitySubscribeNavigate,
          type
        );
        commonSensors.popupEvent('PopupClick', {'popup_type' : '订阅消息', 'popup_name': '订阅消息弹窗', 'button_name': '允许'})
      } else {
        commonSensors.popupEvent('PopupClick', {'popup_type' : '订阅消息', 'popup_name': '订阅消息弹窗', 'button_name': '拒绝'})
      }
    },
    fail(res) {
      // console.log("errormsg---" + JSON.stringify(res));
    },
    complete(res) {},
  });
}

// 订阅订阅消息
async function doSubscribe(
  activitySubscribeId,
  pageAfterSubscribe,
  activitySubscribeNavigate,
  type
) {
  const customerInfo = uni.getStorageSync(CUSTOMER_INFO) || {};
  if (activitySubscribeId) {
    const request = customerInfo.jwt
      ? api.weixinSubscribe
      : api.guestWeixinSubscribe;
    const userSpecialInfo = uni.getStorageSync(USER_SPECICAL_INFO);
    const merchantInfo = uni.getStorageSync(MERCHANT_INFO);

    const query = {
      name: "活动模版消息",
      type: "活动消息",
      appId: getApp().globalData.app_id,
      openId: customerInfo?.openId || userSpecialInfo?.openid,
      merchantId: merchantInfo?.cloudMerchantId,
      params: {
        activitySubscribeId: activitySubscribeId,
      },
    };

    const result = await request({
      method: "POST",
      header: {
        jwt: customerInfo.jwt,
      },
      query,
    });
    // console.log("zlk doSubscribe result:", {
    //   activitySubscribeId,
    //   pageAfterSubscribe,
    //   activitySubscribeNavigate,
    //   query,
    //   type,
    //   result,
    // });
    if (type == "articleSubscribe" || type == "targetActivity") {
      return result;
    } else {
      if (result.code == 1000) {
        tip.success("订阅成功");
        if (!pageAfterSubscribe) {
          return;
        } else {
          if (activitySubscribeNavigate == "false") {
            return;
          }
          uni.navigateTo({
            url: `/${pageAfterSubscribe}`,
          });
        }
      } else {
        tip.plainText(result.msg);
      }
    }
  }
}

function urlToObj(url) {
  let params = {};
  const itemArr = url?.split("&&");
  itemArr.forEach((it) => {
    if (it) {
      const itSplitIndex = it.indexOf("=");
      let key = it.substring(0, itSplitIndex);
      let value = it.substring(itSplitIndex + 1, it.length);
      params[key] = value;
    }
  });
  return params;
}

const objStyle2StrStyle = (obj) => {
  let result = "";
  if (!obj) {
    return result;
  }
  Object.keys(obj).forEach((key) => {
    const v = obj[key];
    const k = key.replace(/([A-Z])/g, "-$1").toLowerCase();
    if (v) {
      result += `${k}: ${v};`;
    }
  });
  return result;
};

module.exports = {
  getCurrentTime: getCurrentTime,
  objLength: objLength,
  displayProp: displayProp,
  sTrim: sTrim,
  replaceColon: replaceColon,
  vailPhone: vailPhone,
  ifSpanish: ifSpanish,
  div: div,
  mul: mul,
  accAdd: accAdd,
  convertStarArray: convertStarArray,
  UTCformat: UTCformat,
  isDuringDate: isDuringDate,
  timeFormat: timeFormat,
  formatTimeStamp: formatTimeStamp,
  noZeroFormat: noZeroFormat,
  getActivitySubscribeDetail,
  getCustomerSubscribeInfo,
  requestSubscribe,
  doSubscribe,
  urlToObj,
  objStyle2StrStyle,
};
